package com.sunxd.vue.infrastructure.utils;

import com.google.common.collect.Lists;
import com.sunxd.vue.bean.AbstractPage;
import com.sunxd.vue.infrastructure.adapter.db.base.Paging;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;

/**
 * @author sun.xd
 * @description: description
 * @date 2022/6/14 20:40
 */
public class PagingUtil {


    /**
     * paging 参数转换
     *
     * @param paging   跑
     * @param function 跑
     * @param <T>      跑
     * @param <R>      跑
     * @return 跑
     */
    public static <T, R> Paging<R> toPaging(Paging<T> paging, Function<T, R> function) {
        if (Objects.isNull(paging) || CollectionUtils.isEmpty(paging.getData())) {
            return new Paging<R>(0L, Lists.newArrayList());
        }
        List<R> rs = ListUtil.toList(paging.getData(), function);
        return new Paging<>(paging.getTotal(), rs);
    }


    /**
     * 增加分页条件
     *
     * @param map       m
     * @param pageModel p
     * @return m
     */
    public static Map<String, Object> addPageParam(Map<String, Object> map, AbstractPage pageModel) {
        int pageNo = pageModel.getPageNo();
        if (pageNo < 1) {
            pageNo = 0;
        } else {
            pageNo -= 1;
        }
        Integer offset = pageNo * pageModel.getPageSize();
        map.put("offset", offset);
        map.put("limit", pageModel.getPageSize());
        return map;

    }

}
